<?php
class RegisterForm extends CFormModel
{
	public $username;
	public $password;
	public $password_repeat;
	public $email;
	public $rememberMe;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			array('username, password, password_repeat, email', 'required'),
			array('password', 'compare'),
			array('username, password, email', 'register'),
		);
	}

	/**
	 * Declares the attribute labels.
	 * If an attribute is not delcared here, it will use the default label
	 * generation algorithm to get its label.
	 */
	public function attributeLabels()
	{
		return array(
			'username' => 'User Name',
			'password' => 'Password',
			'password_repeat' => 'Repeat Password',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function register()
	{
		if(Yii::app()->user->getState('action') == 'register' && !$this->hasErrors())  // we only want to authenticate when no input errors
		{
			$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));

			if ($user !== null)	{
				$this->addError('username','User already exists');
			} else {
				$user = new User;
				$user->username = $this->username;
				$user->password = md5($this->password);
				$user->passkey = md5($user->username.$user->password);
				$user->email = $this->email;
				
				if ($user->save()) {
					Yii::app()->user->setState('action', '');
					$user->role = 'user';
					$user->permissions = 0 + Yii::app()->db->createCommand(
							'SELECT base_permissions from roles where name=\'user\''
						)->queryScalar();
					$identity = new UserIdentity($this->username, md5($this->password));
					if ($identity->authenticate())
						Yii::app()->user->login($identity, 0);
				} else {
					$this->addErrors($user->getErrors());
				}
			}

		}
	}

}

?>
